from flask import Flask
from flask_cors import CORS
from configs.db_config import MySQLPools
from configs.blueprints_config import RegisterBlueprints
from configs.middleware_config import Middleware
from configs.nosql_config import RedisClient, RedisCache
from configs.websocket_config import create_server


def create_app():
    """工厂函数，用于将所有组件全局注册"""
    app = Flask(__name__)
    """解决数据编码问题"""
    app.json.ensure_ascii = False
    CORS(app, resources=r'/*')
    mysql_pool = MySQLPools()  # 初始化 MySQL 连接池
    pool_store = mysql_pool.DynamicCreateConnectionPools()  # 动态创建连接池
    if pool_store: app.config['POOL_STORE'] = pool_store  # 全局注册连接池
    redis_client = RedisClient().redis_client
    app.config['REDIS_CLIENT'] = redis_client
    RedisCache.init_app(app=app)

    Middleware(app)  # 注册钩子函数
    app, socketio = create_server(app)
    RegisterBlueprints(app)  # 注册蓝图
    return app, socketio
